//
//  FSScrollContentViewController.m
//  FSScrollViewNestTableViewDemo
//
//  Created by huim on 2017/5/23.
//  Copyright © 2017年 fengshun. All rights reserved.
//

#import "FSScrollContentViewController.h"
#import "MJRefresh.h"
#import "XMGRefreshHeader.h"
#import "XMGRefreshFooter.h"
#import "HomeCollecLayout.h"
#import "HomeCollectionCell.h"
#import "GoodsInfoModel.h"
#import "GoodDetailController.h"
#import "BaseNavigationController.h"
/**
 * 随机数据
 */
#define RandomData [NSString stringWithFormat:@"随机数据---%d", arc4random_uniform(1000000)]

@interface FSScrollContentViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic, assign) BOOL fingerIsTouch;

@property (nonatomic, assign) NSInteger curpage;

@property (nonatomic, assign) NSString *pageCount;

/** <#note#> */
@property (nonatomic, strong) NSMutableArray<GoodsInfoModel *> *dataModels;

@end

@implementation FSScrollContentViewController

- (UICollectionView *)collectionView{
    
    if (!_collectionView) {
      
        UICollectionView *temp = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, KScreenW,KScreenH - (IPhoneX ? 88 : 64) - 36) collectionViewLayout:[[HomeCollecLayout alloc]init]];
        
        
        
        [temp registerNib:[UINib nibWithNibName:NSStringFromClass([HomeCollectionCell class]) bundle:nil] forCellWithReuseIdentifier:[HomeCollectionCell identifierStr]];

         temp.showsVerticalScrollIndicator = NO;
        temp.delegate = self;
        temp.dataSource = self;
        _collectionView = temp;
        
        [self.view addSubview:_collectionView];
        
    }
    
   
    return _collectionView;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSLog(@"---%@",self.title);
}

//UICollectionView: 0x14e885200
//UICollectionView: 0x14e08e800
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.collectionView.backgroundColor = lineGray;
    
    NSLog(@"%@fsdfdsfds",self.collectionView);
    
    [self loadData];

    
    MJWeakSelf;
    weakSelf.collectionView.mj_footer = [XMGRefreshFooter footerWithRefreshingBlock:^{
        
        [self loadMoreData];

        
    }];
    
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    if (@available(iOS 11.0, *)) {

        self.collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        
    }
    
    
    self.collectionView.contentInset = UIEdgeInsetsMake(0, 0, IPhoneX ? 119 : 85, 0);
    
    
    
    NSLog(@"%@+++++++++++",self.title);
    
//    [self.collectionView.mj_footer setAutomaticallyHidden:YES];
    
    
}



- (void)loadData{
    self.curpage = 1;
    
    NSMutableDictionary *parmars = [NSMutableDictionary dictionary];
    
    parmars[@"curpage"] = @"1";
    

    
    if ([self.title isEqualToString:@"人气"]) {
        parmars[@"order_type"] = @"1";
    } else if ([self.title isEqualToString:@"最新"]){
        parmars[@"order_type"] = @"2";
    }else if ([self.title isEqualToString:@"进度"]){
        parmars[@"order_type"] = @"3";
    }else{
//        if (<#condition#>) {
//            <#statements#>
//        } else {
//            <#statements#>
//        }
        parmars[@"order_type"] = @"4";
        
    }
    

    
    
    MJWeakSelf;
    [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:POST_METHOD URLPath:@"index.php/Api/Dbindex/get_more" parameters:parmars completionHandler:^(id responseObject, NSError *error) {
        
        if (!error) {
            
//            NSLog(@"%@",[responseObject mj_JSONString]);
            
            weakSelf.pageCount = responseObject[@"data"][@"count"];
            
            self.dataModels = [GoodsInfoModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"list"]];
            
            if ([weakSelf.pageCount isEqualToString:@"1"]) {
                
                [weakSelf.collectionView.mj_footer endRefreshingWithNoMoreData];
                
            }
            
            
            
            [weakSelf.collectionView reloadData];
            
        } else {
            
            
            [SVProgressHUD showErrorWithStatus:error.domain];
            
        }
        
        
        
    }];
    
    
}





- (void)loadMoreData
{
    self.curpage ++;
    
    NSMutableDictionary *parmars = [NSMutableDictionary dictionary];

    parmars[@"curpage"] = [NSString stringWithFormat:@"%ld",(long)self.curpage];
    
    
    if ([self.title isEqualToString:@"人气"]) {
        parmars[@"order_type"] = @"1";
    } else if ([self.title isEqualToString:@"最新"]){
        parmars[@"order_type"] = @"2";
    }else if ([self.title isEqualToString:@"进度"]){
        
        parmars[@"order_type"] = @"3";
        
    }else{
        
        
        //        if (<#condition#>) {
        //            <#statements#>
        //        } else {
        //            <#statements#>
        //        }
        
        
        parmars[@"order_type"] = @"4";
        
    }
    
    
    
    
    MJWeakSelf;
    [[NetworkTools shareNetworkTools]sendRequestWithHttpMethod:POST_METHOD URLPath:@"index.php/Api/Dbindex/get_more" parameters:parmars completionHandler:^(id responseObject, NSError *error) {
        
        if (!error) {
            
            
            NSMutableArray<GoodsInfoModel *> *temp = [GoodsInfoModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"list"]];
            
            [weakSelf.dataModels addObjectsFromArray:temp];
            
            if (weakSelf.pageCount.integerValue == self.curpage) {
                
                [weakSelf.collectionView.mj_footer endRefreshingWithNoMoreData];
                
            } else {
                
                [weakSelf.collectionView.mj_footer endRefreshing];
                
                
            }
            
            
            
            [weakSelf.collectionView reloadData];
            
        } else {
            
            [weakSelf.collectionView.mj_footer endRefreshing];

            [SVProgressHUD showErrorWithStatus:error.domain];
            
        }
        
        
        
    }];
    
    
    
    
}

#pragma mark Setter
- (void)setIsRefresh:(BOOL)isRefresh
{
    _isRefresh = isRefresh;
    [self loadData];
}

#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    if (self.dataModels == nil) {
        return 0;
    }
    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    if (self.dataModels == nil) {
        return 0;
    }
    
    return self.dataModels.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    HomeCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:[HomeCollectionCell identifierStr] forIndexPath:indexPath];
    
    cell.model = self.dataModels[indexPath.item];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    GoodDetailController *temp = [[GoodDetailController alloc]init];
    
    BaseNavigationController *nav = [UIApplication sharedApplication].keyWindow.rootViewController.childViewControllers[0];
    
    [nav pushViewController:temp animated:YES   ];
    
    
}




#pragma mark UIScrollView
//判断屏幕触碰状态
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    NSLog(@"接触屏幕");
    self.fingerIsTouch = YES;
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    NSLog(@"离开屏幕");
    self.fingerIsTouch = NO;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (!self.vcCanScroll) {
        scrollView.contentOffset = CGPointZero;
    }
    if (scrollView.contentOffset.y <= 0) {
//        if (!self.fingerIsTouch) {//这里的作用是在手指离开屏幕后也不让显示主视图，具体可以自己看看效果
//            return;
//        }
        self.vcCanScroll = NO;
        scrollView.contentOffset = CGPointZero;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"leaveTop" object:nil];//到顶通知父视图改变状态
    }
//    self.tableView.showsVerticalScrollIndicator = _vcCanScroll?YES:NO;
}




@end
